package com.cx.mall.demo.controller;

import com.cx.mall.demo.service.LoginService;
import com.cx.mall.demo.service.UserService;
import com.cx.mall.demo.utils.JwtUtils;
import com.cx.mall.demo.utils.ResponseMessageEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/api/login")
@Tag(name = "登录接口", description = "提供验证码获取和验证码登录功能")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private UserService userService;

    /**
     * 获取验证码
     */
    @PostMapping("/getCode")
    public ResponseEntity<Map<String, Object>> getVerificationCode(@RequestParam String phoneNumber) {
        Map<String, Object> response = new HashMap<>();

        if (!isValidPhone(phoneNumber)) {
            response.put("success", false);
            response.put("message", ResponseMessageEnum.INVALID_PHONE.getMessage());
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }

        try {
            if (!userService.isPhoneRegistered(phoneNumber)) {
                response.put("success", false);
                response.put("message", ResponseMessageEnum.PHONE_UNREGISTERED.getMessage());
                return ResponseEntity.ok(response);
            }
            boolean success = loginService.getLoginCode(phoneNumber);
            response.put("success", success);
            response.put("message", success ?
                    ResponseMessageEnum.CODE_SEND_SUCCESS.getMessage() :
                    ResponseMessageEnum.CODE_SEND_FAIL.getMessage());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", ResponseMessageEnum.SYSTEM_ERROR.getMessage(e.getMessage()));
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 验证码登录
     */
    @PostMapping("/verify")
    public ResponseEntity<Map<String, Object>> login(@RequestParam String phoneNumber, @RequestParam String code) {
        Map<String, Object> response = new HashMap<>();

        if (!isValidPhone(phoneNumber)) {
            response.put("success", false);
            response.put("message", ResponseMessageEnum.INVALID_PHONE.getMessage());
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }
        if (!isValidCode(code)) {
            response.put("success", false);
            response.put("message", ResponseMessageEnum.INVALID_CODE.getMessage());
            return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
        }

        try {
            LoginService.LoginResult result = loginService.loginWithCode(phoneNumber, code);
            response.put("success", result.isSuccess());
            response.put("message", result.getMessage());
            if (result.isSuccess()) {
                response.put("data", result.getToken());
            }
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", ResponseMessageEnum.SYSTEM_ERROR.getMessage(e.getMessage()));//
            return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    /**
     * 手机号格式校验
     */
    private boolean isValidPhone(String phone) {
        return StringUtils.hasText(phone) && phone.matches("^1[3-9]\\d{9}$");
    }

    /**
     * 验证码格式校验
     */
    private boolean isValidCode(String code) {
        return StringUtils.hasText(code) && code.matches("^\\d{6}$");
    }

    @PostMapping("/refreshToken")
    public ResponseEntity<Map<String, Object>> refreshToken(@RequestHeader("Authorization") String oldToken) {
        Map<String, Object> response = new HashMap<>();

        if (oldToken == null || oldToken.trim().isEmpty()) {
            response.put("success", false);
            response.put("message", ResponseMessageEnum.TOKEN_EMPTY.getMessage());
            return ResponseEntity.badRequest().body(response);
        }

        String newToken = JwtUtils.refreshToken(oldToken);
        if (newToken != null) {
            response.put("success", true);
            response.put("message", ResponseMessageEnum.TOKEN_REFRESH_SUCCESS.getMessage());
            response.put("data", newToken);
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", ResponseMessageEnum.TOKEN_INVALID_OR_EXPIRED.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}